local getDbVal = InstanceTimer.getDbVal
local setDbVal = InstanceTimer.setDbVal

local frame = CreateFrame("Frame", "InstanceTimerConfigFrame", InstanceTimerFrame)
local font = GameFontNormal:GetFont()

local top = -20
local left = 20
local uncheckColor = { 0.3, 0.3, 0.3, 0.8 }
local checkColor = { 0, 0.8, 0, 0.8 }
local init = 0

frame:SetWidth(260)
-- frame:SetHeight(420)
frame:ClearAllPoints()
frame:SetPoint("CENTER", UIParent, "CENTER")
frame:SetFrameLevel(15)
frame:Hide()

frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", function() frame:StartMoving() end)
frame:SetScript("OnDragStop", function() frame:StopMovingOrSizing() end)

frame.texture = frame:CreateTexture(nil, "BACKGROUND")
frame.texture:SetTexture(0, 0, 0, 0.9)
frame.texture:SetAllPoints(frame)

frame.title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
frame.title:SetFont(font, 16)
frame.title:SetText("副本计时计次工具  " .. GetAddOnMetadata("InstanceTimer", "Version"))
frame.title:SetPoint("TOP", frame, "TOP", 0, top)
top = top - 45

frame.show = function()
  if init == 0 then
    frame.init()
  else
    for _, opt in ipairs(frame.configOptions) do
      if type(opt.updateVal) == 'function' then
        opt.updateVal()
      end
    end
  end
  frame:Show()
end

frame.hide = function()
  frame:Hide()
end

frame.toggle = function()
  if frame:IsVisible() then
    frame.hide()
  else
    frame.show()
  end
end

frame.configOptions = {}
local addCheck = function(name, key, text, hook, nowrap)
  -- 创建一个Frame作为复选框容器
  local myCheckbox = CreateFrame("CheckButton", frame:GetName() .. "Check" .. name, frame)
  myCheckbox:SetWidth(16)
  myCheckbox:SetHeight(16)

  -- -- 创建未选中状态的纹理
  local uncheckedTexture = myCheckbox:CreateTexture(nil, "ARTWORK")
  uncheckedTexture:SetAllPoints(myCheckbox)
  -- uncheckedTexture:SetCTexture("Interface\\Buttons\\UI-CheckBox-Up")
  uncheckedTexture:SetTexture(unpack(uncheckColor))

  -- -- 创建选中状态的纹理，初始隐藏
  local checkedTexture = myCheckbox:CreateTexture(nil, "ARTWORK")
  checkedTexture:SetAllPoints(myCheckbox)
  -- checkedTexture:SetTexture("Interface\\Buttons\\UI-CheckBox-Checked")
  checkedTexture:SetTexture(unpack(checkColor))
  checkedTexture:Hide()

  -- 记录复选框状态
  local isChecked = getDbVal(key) == true
  myCheckbox:SetChecked(isChecked)

  local updateTexture = function()
    if myCheckbox:GetChecked() then
      checkedTexture:Show()
      uncheckedTexture:Hide()
    else
      checkedTexture:Hide()
      uncheckedTexture:Show()
    end
  end

  updateTexture()

  -- 定义点击处理函数
  myCheckbox:SetScript("OnClick", function()
    isChecked = (not myCheckbox:GetChecked()) == false
    myCheckbox:SetChecked(isChecked)
    updateTexture()
    setDbVal(key, isChecked)
    InstanceTimer.trigger('OPTIONS_CHANGED', key, isChecked)
  end)

  myCheckbox.text = myCheckbox:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  myCheckbox.text:SetPoint("TOPLEFT", frame, "TOPLEFT", left, top - 3)
  myCheckbox.text:SetJustifyH("LEFT")
  myCheckbox.text:SetFont(font, 14)
  myCheckbox.text:SetText(text)
  myCheckbox:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -left, top)

  myCheckbox.oname = key
  myCheckbox.setVal = function(checked)
    myCheckbox:SetChecked(checked)
    updateTexture()
  end
  myCheckbox.updateVal = function()
    local checked = getDbVal(key) == true
    myCheckbox:SetChecked(checked)
    updateTexture()
  end

  table.insert(frame.configOptions, myCheckbox)

  if not nowrap then
    top = top - myCheckbox:GetHeight() - 8
  end
end

local bottom = 20
local addButton = function(name, text, width, handler, nowrap)
  local button = CreateFrame("Button", frame:GetName() .. "Button" .. name, frame, "UIPanelButtonTemplate")

  button.text = button:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  button.text:SetAllPoints(button)
  button.text:SetFont(font, 14)
  button.text:SetJustifyH("CENTER")
  button.text:SetJustifyV("MIDDLE")
  button.text:SetText(text)

  button:SetScript("OnDoubleClick", function()
    handler()
    frame:Hide()
  end)
  button:SetWidth(width or 58)
  button:SetHeight(20)

  button:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", left, bottom)
  if nowrap then
    left = left + button:GetWidth() + 5
  else
    left = 20
    bottom = bottom + 30
  end
end

frame.setVal = function(name, val)
  for _, option in ipairs(frame.configOptions) do
    if name == option.oname then
      option.setVal(val)
    end
  end
end

frame.init = function()
  addCheck("ShowTimer", "showtimer", "显示计时器")
  addCheck("ShowBoomCounter", "showcounter", "显示爆本监视")
  addCheck("Locked", "locked", "锁定位置")
  addCheck("AutoStartTimer", "timer.autostart", "进本开始计时")
  addCheck("AutoReset", "timer.autoreset", "进本计时归零")
  addCheck("AutoStop", "timer.autostop", "出本停止计时")
  addCheck("AutoResetOut", "timer.autoresetout", "出本计时归零")
  addCheck("Through", "through", "点击穿透")
  addCheck("AutoLog", "boomcounter.autolog", "进本记录次数")
  addCheck("AutoLogRaid", "boomcounter.lograid", "记录团本")
  addCheck("ShowProgressAlways", "boomcounter.showprogressalways", "充能进度常驻")
  addCheck("HideTimerNotInInstance", "timer.hidenotininstance", "不在副本时隐藏计时器")
  -- addCheck("BoomCounterHiddenLimit", "boomcounter.hiddenlimit", "剩余次数> n 时隐藏副本计次")

  top = top - 10
  local slider = CreateFrame("Slider", frame:GetName() .. "SliderBoomCounterHiddenLimit", frame, "OptionsSliderTemplate")
  slider:SetMinMaxValues(0, 5)
  slider:SetValueStep(1)
  slider:SetWidth(75)
  getglobal(slider:GetName() .. 'Low'):Hide()
  getglobal(slider:GetName() .. 'High'):Hide()

  local sliderKey = "boomcounter.hiddenlimit"
  local labelLeft = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  labelLeft:SetPoint("TOPLEFT", frame, "TOPLEFT", left, top)
  slider:SetPoint("LEFT", labelLeft, "RIGHT", 10, 0)
  local labelRight = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  labelRight:SetPoint("LEFT", slider, "RIGHT", 10, 0)
  labelLeft:SetText("可用次数大于")
  labelRight:SetText("隐藏计次")
  slider:SetScript("OnValueChanged", function()
    -- cb.vlabel:SetText(roundNum(this:GetValue(), 2))
    setDbVal(sliderKey, this:GetValue())
    slider.vlabel:SetText(slider:GetValue())
    InstanceTimer.trigger('OPTIONS_CHANGED', sliderKey, slider:GetValue())
  end)

  slider.oname = sliderKey
  slider.vlabel = slider:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  slider.vlabel:SetPoint("TOP", slider, "TOP", 0, 10)
  slider.setVal = function(newValue)
    slider:SetValue(newValue)
    slider.vlabel:SetText(slider:GetValue())
  end
  slider.updateVal = function()
    slider:SetValue(getDbVal(sliderKey))
    slider.vlabel:SetText(slider:GetValue())
  end
  slider.updateVal()
  table.insert(frame.configOptions, slider)

  top = top - 30

  addButton("FullStopTimer", "停止计时", 100, function()
    if InstanceTimer.timer then
      InstanceTimer.timer.stop(true)
    end
  end)

  addButton("Increment", "记录副本", 100, function()
    if InstanceTimer.boomcounter then
      InstanceTimer.boomcounter.addLog()
    end
  end, true)
  addButton("Decrement", "删除末次", 100, function()
    if InstanceTimer.boomcounter then
      if InstanceTimer.boomcounter.getTimesLeft() < 5 then
        InstanceTimer.boomcounter.removeLastLog()
      end
    end
  end)
  addButton("ClearLogs", "清空", 100, function()
    if InstanceTimer.boomcounter then
      InstanceTimer.boomcounter.clearLogs()
    end
  end, true)
  addButton("CoverLog", "覆盖(重进)", 100, function()
    if InstanceTimer.boomcounter then
      InstanceTimer.boomcounter.coverLog()
    end
  end)

  frame:SetHeight(-top + 110)

  init = 1
end

local closeButton = CreateFrame("Button", nil, frame)
-- 设置按钮的大小
closeButton:SetWidth(20)
closeButton:SetHeight(20)
-- 设置按钮的位置在 frame 内部的右上角
closeButton:SetPoint("TOPLEFT", frame, "TOPRIGHT", 0, 0)

-- 设置按钮的背景和边框
closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
closeButton:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")

-- 设置按钮的点击事件，点击后隐藏 frame
closeButton:SetScript("OnClick", function()
  frame.hide()
end)

InstanceTimer.config = frame
table.insert(UISpecialFrames, frame:GetName())
